package com.study.spring.disruptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReferenceArray;

/**
 * 功能描述：实现自己的队列
 * <p>
 * author: ZACK
 * date: 2021/5/20 8:10
 */
public class MyQueue {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyQueue.class);

    private final AtomicReferenceArray<Object> array;

    private final AtomicLong head;
    private final AtomicLong tail;

    private final int m;


    public MyQueue(int capacity) {

        if (capacity < 0 || capacity % 2 != 0) {
            throw new IllegalArgumentException("capacity must be power of 2!");
        }

        m = capacity - 1;

        AtomicLong[] atomicLongs = new AtomicLong[30];
        for (int i = 0; i < atomicLongs.length; i++) {
            atomicLongs[i] = new AtomicLong();
        }
        head = atomicLongs[3];
        tail = atomicLongs[20];
        array = new AtomicReferenceArray<>(new Object[capacity]);
    }

    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue(2048);

        new Thread(() -> {
            int i = 0;
            while (true) {
                Integer o = i++;
                myQueue.put(o);
            }
        }, "produce").start();

        new Thread(() -> {
            while (true) {
                myQueue.take();
            }
        }, "consumer1").start();

        new Thread(() -> {
            while (true) {
                myQueue.take();
            }
        }, "consumer2").start();

        new Thread(() -> {
            while (true) {
                myQueue.take();
            }
        }, "consumer3").start();

    }

    public void put(Object object) {
        int index = (int) (head.getAndIncrement() & m);
        while (!array.compareAndSet(index, null, object)) {
        }
    }

    public Object take() {
        Object result;
//        tail.compareAndSet()
        int index = (int) (tail.getAndIncrement() & m);
        while ((result = array.getAndSet(index, null)) == null) {
        }
        return result;
    }
}
